package com.wr.springbootadmin.utils;


import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import javax.net.ssl.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
 * @author 王瑞
 * @description: TODO
 * @date 2020/12/18  14:19
 */
public class UploadImg {


    private static InputStream getInputStream(String imgUrl) {
        InputStream inputStream = null;
        try {
            HttpsURLConnection httpURLConnection = (HttpsURLConnection) new URL(imgUrl).openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");
            httpURLConnection.setRequestProperty("Accept-Encoding", "gzip");
            httpURLConnection.setRequestProperty("Referer", "no-referrer");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setConnectTimeout(15000);
            httpURLConnection.setReadTimeout(20000);
            inputStream = httpURLConnection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }


    public static boolean downloadImg(String imgUrl, String path) {
        boolean flag = true;
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();//创建路径
        }
        try {
            InputStream inputStream = getInputStream(imgUrl);
            FileUtils.copyToFile(inputStream, file);
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }


    public static void downloadA(String downloadUrl, String path) {
        URL url = null;
        DataInputStream dataInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            url = new URL(downloadUrl);
            dataInputStream = new DataInputStream(url.openStream());
            fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param downloadUrl 文件链接地址
     * @param filename    保存文件名
     * @param filePath    保存文件路径
     */

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    private static InputStream inputStream = null;
    private static OutputStream outputStream = null;

    public static String downloadB(String downloadUrl, String filename, String filePath) {
        URL url = null;
        URLConnection con = null;
        String imgLocalPath = "";
        try {
            url = new URL(downloadUrl);
            // 打开连接
            con = (HttpURLConnection) url.openConnection();
            // 请求超时:5s
            con.setConnectTimeout(5 * 1000);
            inputStream = con.getInputStream();

            byte[] bytes = new byte[1024];
            // 读取到的数据长度
            int length;
            File savePath = new File(filePath);
            if (!savePath.exists()) {
                // 如果不存在当前文件夹，则创建该文件夹
                boolean mkdir = savePath.mkdirs();
                if (!mkdir) {
                    System.out.println("创建文件夹失败");
                }
            }
            outputStream = new FileOutputStream(savePath.getPath() + "\\" + filename);
            // 读取
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }

            imgLocalPath = savePath.getPath() + "\\" + filename;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return imgLocalPath;
    }


    public static String downloadBShiJu(String downloadUrl, String filename, String filePath) {
        URL url = null;
        String imgLocalPath = "";
        try {
            url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
           // HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            if (conn instanceof HttpsURLConnection) {
                //url = new URL(null,downloadUrl,new sun.net.www.protocol.https.Handler());
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
                ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());
                ((HttpsURLConnection) conn).setHostnameVerifier(new NullHostNameVerifier());
            }
            conn.connect();
            // 请求超时:5s
            conn.setConnectTimeout(5 * 1000);
            inputStream = conn.getInputStream();

            byte[] bytes = new byte[1024];
            // 读取到的数据长度
            int length;
            File savePath = new File(filePath);
            if (!savePath.exists()) {
                // 如果不存在当前文件夹，则创建该文件夹
                boolean mkdir = savePath.mkdirs();
                if (!mkdir) {
                    System.out.println("创建文件夹失败");
                }
            }
            outputStream = new FileOutputStream(savePath.getPath() + "\\" + filename);
            // 读取
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }

            imgLocalPath = savePath.getPath() + "\\" + filename;
        } catch (Exception e) {
            e.printStackTrace();
            return imgLocalPath;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return imgLocalPath;
    }





    /* public static String downloadBShiJu(String downloadUrl, String filename, String filePath) throws NoSuchAlgorithmException, IOException, KeyManagementException {
         //设置可通过ip地址访问https请求
         HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
         TrustManager[] tm = {new MyX509TrustManager()};
         SSLContext sslContext = SSLContext.getInstance("TLS");
         sslContext.init(null, tm, new java.security.SecureRandom());
         // 从上述SSLContext对象中得到SSLSocketFactory对象
         SSLSocketFactory ssf = sslContext.getSocketFactory();

         URL url = new URL(downloadUrl);
         HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
         con.setSSLSocketFactory(ssf);
         con.setRequestMethod("POST"); // 设置以POST方式提交数据
         con.setDoInput(true); // 打开输入流，以便从服务器获取数据
         con.setDoOutput(true);// 打开输出流，以便向服务器提交数据

         String imgLocalPath = "";
         try {
             url = new URL(downloadUrl);


             HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
             if (url.getProtocol().toLowerCase().equals("https")) {
                 https.setHostnameVerifier(DO_NOT_VERIFY);
                 con = https;
             }
             // 请求超时:5s
             con.setConnectTimeout(5 * 1000);
             inputStream = con.getInputStream();

             byte[] bytes = new byte[1024];
             // 读取到的数据长度
             int length;
             File savePath = new File(filePath);
             if (!savePath.exists()) {
                 // 如果不存在当前文件夹，则创建该文件夹
                 boolean mkdir = savePath.mkdirs();
                 if (!mkdir) {
                     System.out.println("创建文件夹失败");
                 }
             }
             outputStream = new FileOutputStream(savePath.getPath() + "\\" + filename);
             // 读取
             while ((length = inputStream.read(bytes)) != -1) {
                 outputStream.write(bytes, 0, length);
             }

             imgLocalPath = savePath.getPath() + "\\" + filename;
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (inputStream != null) {
                 try {
                     inputStream.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
             if (outputStream != null) {
                 try {
                     outputStream.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }

         return imgLocalPath;
     }
 */
    public static void CloseResource() {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    public static boolean cropImage(InputStream inputStream, int x, int y, int w, int h, String sufix, File file) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        bufferedImage = bufferedImage.getSubimage(x, y, w, h);
        return ImageIO.write(bufferedImage, sufix, file);
    }


}
